<template>
  <div ref="echartDom"></div>
</template>

<script setup>
import {ref, defineProps, onMounted, onUnmounted, inject, shallowRef, defineExpose} from 'vue'
import {pxToRem} from "@/utils/index";

const props = defineProps({
  pieData: {
    type: Array,
    default: () => []
  },
  dialogData: {
    type: Object,
    default: () => ({
      fontSizeTimes: 1
    })
  },
});

const echartDom = ref(null);
const myChart = shallowRef(null);
const echarts = inject('echarts');

const initEchart = () => {
  if (echartDom.value) {
    myChart.value = echarts.init(echartDom.value);
    let totalValue = 0
    let tempDataList = props?.pieData?.seriesData
    for (let i = 0; i < tempDataList.length; i++) {
      totalValue += tempDataList[i].value;
    }
    let option = {
      color: ['#2eb8f6', '#7fc757', '#eb7f8c', '#face91', '#03a7ef', '#7ec857'],
      title: {
        text: '{a|}',
        textStyle: {
          color: 'white',
          rich: {
            a: {
              fontSize: pxToRem(16 * props?.dialogData?.fontSizeTimes),
              align: "center",
            },
            b: {
              fontSize: pxToRem(14 * props?.dialogData?.fontSizeTimes),
              align: "center",
            }
          },
        },
        itemGap: pxToRem(-85 * props?.dialogData?.fontSizeTimes),
        subtext: '{c|占比}',
        subtextStyle: {
          rich: {
            c: {
              width: pxToRem(50 * props?.dialogData?.fontSizeTimes),
              fontSize: pxToRem(14 * props?.dialogData?.fontSizeTimes),
              color: 'white',
              align: "right",
            },
          }
        },
        x: props?.dialogData?.fontSizeTimes === 1 ? '80%' : '70%',
        y: "38%",
      },
      tooltip: {
        show: true,
        formatter: '{b}{c}万元 \t{d}%'
      },
      legend: {
        top: 'center',
        right: props?.dialogData?.fontSizeTimes === 1 ? '2%' : '19%',
        itemHeight: pxToRem(12 * props?.dialogData?.fontSizeTimes),
        itemWidth: pxToRem(12 * props?.dialogData?.fontSizeTimes),
        y: '20%',
        width: pxToRem(40 * props?.dialogData?.fontSizeTimes),
        padding: [0, 0, 0],
        textStyle: {
          rich: {
            one: {
              width: pxToRem(props?.dialogData?.fontSizeTimes === 1 ? 80 : 200),
              height: pxToRem(30 * props?.dialogData?.fontSizeTimes),
              color: 'white',
              fontSize: pxToRem(12 * props?.dialogData?.fontSizeTimes),
            }
          },
        },
        formatter: (name) => {
          const targetObj = tempDataList.find(x => x.name === name)
          const rate = totalValue !== 0 ? (targetObj.value / totalValue * 100).toFixed(2) : 0
          if (name.length > 3 && props?.dialogData?.fontSizeTimes === 1) {
            // 如果名称长度超过10，则截取前5个字符和后5个字符，中间使用省略号
            return `{one|${name.substring(0, 3)}...} {one|${rate}%}`;
          } else {
            return `{one|${name}} {one|${rate}%}`;
          }
        },
        tooltip: {
          show: true,
          formatter: (res) => {
            const targetObj = tempDataList.find(x => x.name === res.name)
            const rate = totalValue !== 0 ? (targetObj.value / totalValue * 100).toFixed(2) : 0
            return `名称：${res.name}</br>占比：${rate}%`;
          }
        },
      },
      series: [
        {
          type: 'pie',
          radius: ['50%', '65%'],
          center: ['25%', '50%'],
          clockwise: true,
          zIndex: 1,
          avoidLabelOverlap: true,
          label: {
            show: false,
            position: 'center'
          },
          labelLine: {
            //label线的长度
            show: false,
          },
          emphasis: {
            label: {
              show: true,
              fontSize: pxToRem(14 * props?.dialogData?.fontSizeTimes),
              formatter: (params) => {
                const {name, value} = params.data;
                let rate = totalValue ? (value / totalValue * 100).toFixed(2) : 0
                return `{a|${rate}%}\n{b|${name}}`;
              },
              textStyle: {
                color: 'white',
                rich: {
                  a: {
                    fontSize: pxToRem(14 * props?.dialogData?.fontSizeTimes),
                    align: "center",
                  },
                  b: {
                    fontSize: pxToRem(14 * props?.dialogData?.fontSizeTimes),
                    align: "center",
                  }
                },
              },
            }
          },
          itemStyle: {
            normal: {
              borderWidth: pxToRem(5 * props?.dialogData?.fontSizeTimes),
            }
          },
          data: props?.pieData?.seriesData
        }
      ]
    }
    option && myChart.value.setOption(option, true);
  }
}

const updateChart = () => {
  if (myChart.value) {
    myChart.value.dispose(); // 销毁旧图表实例
  }
  initEchart();
};

defineExpose({
  updateChart
})

onMounted(() => {
  initEchart();
  window.addEventListener("resize", updateChart);
})

onUnmounted(() => {
  window.removeEventListener("resize", updateChart);
})
</script>

<style scoped lang="less">
.h180 {
  height: 180px;
}
.dialog-h180 {
  width: 919px;
  height: 500px;
}
</style>